﻿using _80X_CG_Frame.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using _80X_CG_Frame.Protocols;
using _80X_CG_Frame.Utils;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace _80X_CG_Frame.Objects
{
    /// <summary>
    /// 相机算法接口实现
    /// </summary>
    public class Cameras : AsyncClient, ICameras
    {
        Camera camera;
        Dictionary<string, int> last_snap_count;
        public Cameras() : base()
        {
            last_snap_count = new Dictionary<string, int>();
            //Camera.CoilAddress.Values.Select(c => last_snap_count[c] = -1);
            foreach (string s in Camera.BlockAddress.Values)
            {
                last_snap_count[s] = -1;
            }
        }
        
        public async Task<bool> CamConnectAsync(string address, int times = 5)
        {
            bool connected = await ConnectAsync(address, times);
            if (connected)
                camera = new Camera(client);
            return connected;
        }
  
        public Result GetTaskStatus1(int id)
        {
            Result result = Result.None;
            if (IsConnect)
            {

                List<string> result_str = new List<string>();
                camera.GetTaskStatus(id, ref result_str);
                switch (result_str[0])
                {
                    case "01":
                        result = Result.NotLocate;
                        break;
                    case "02":
                        result = Result.Failed;
                        break;
                    case "03":
                        result = Result.Passed;
                        break;
                    default:
                        break;
                }
            }
            return result;
        }
        

        public Result GetTaskStatus(int id)
        {
            Result result = Result.None;
            if (IsConnect)
            {

                if (last_snap_count[Camera.BlockAddress[id]] == -1 || last_snap_count[Camera.BlockAddress[id]] == 0)
                {
                    System.Threading.Thread.Sleep(500);
                }

                List<string> result_str = new List<string>();
                camera.GetTaskStatus(id, ref result_str);

                var snap_temp = Convert.ToInt32(result_str[1], 16);
                if (last_snap_count[Camera.BlockAddress[id]] != snap_temp)
                {
                    switch (result_str[0])
                    {
                        case "01":
                            result = Result.NotLocate;
                            break;
                        case "02":
                            result = Result.Failed;
                            break;
                        case "03":
                            result = Result.Passed;
                            break;
                        default:
                            break;
                    }
                }
                if(result!=Result.None)
                    last_snap_count[Camera.BlockAddress[id]] = snap_temp;

            }
            return result;
        }
        /// <summary>
        /// 选择相机任务
        /// </summary>
        /// <param name="id"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public bool SelectTask(int id, int mode)
        {
            if(IsConnect)
            {
                string result = "";
                camera.SelectTask(id, mode, ref result);

                return true;
            }
            return false;
        }
        /// <summary>
        /// 取相机Arc(Circle)Tool 圆与圆弧结果
        /// </summary>
        /// <param name="start_address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string[] GetCircleResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseCircleData(result);
                return str;
            }
            return new string[] { };
        }

        /// <summary>
        /// ContourMatch轮廓匹配结果
        /// </summary>
        /// <param name="start_address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string[] GetContourResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseContourData(result);
                return str;
            }
            return new string[] { };
        }

        public string[] GetContourMatchResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseContourMatchData(result);
                return str;
            }
            return new string[] { };
        }
        /// <summary>
        /// BlobLocator（bolb定位器）
        /// </summary>
        /// <param name="start_address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string[] GetBlobResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseBlobData(result);
                return str;
            }
            return new string[] { };
        }
        public string[] GetStatusBlobResult(string start_address, int length,ref Result result_status)
        {
            //result_status = Result.None;
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseStatusBlobData(result);
                switch (str[0])
                {
                    case "01":
                        result_status = Result.NotLocate;
                        break;
                    case "02":
                        result_status = Result.Failed;
                        break;
                    case "03":
                        result_status = Result.Passed;
                        break;
                    default:
                        break;
                }
                return str;
            }
            return new string[] { };
        }
        /// <summary>
        ///  BlobLocator（bolb定位器）取SubBlob
        /// </summary>
        /// <param name="start_address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string[] GetSubBlobResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParsesSubBlobData(result);
                return str;
            }
            return new string[] { };
        }
        /// <summary>
        /// ObjectLocator目标定位器
        /// </summary>
        /// <param name="start_address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string[] GetObjectResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseObjectData(result);
                return str;
            }
            return new string[] { };
        }
        /// <summary>
        /// EdgeTool 边缘
        /// </summary>
        /// <param name="start_address"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string[] GetEdgeResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                string[] str = camera.ParseEdgeData(result);
                return str;
            }
            return new string[] { };
        }
        public int GetBlobCountResult(string start_address, int length)
        {
            if (IsConnect)
            {
                string result = "";
                camera.GetResult(start_address, length, ref result);
                int count = Convert.ToInt32(result.Substring(18 + 9 * 4, 4), 16);
                return count;
            }
            return 0;
        }

        public bool GetCameraBusyResult(int id)
        {

            string start_address = Camera.CoilRegisterAddress[id];

            if (IsConnect)
            {
                string result = "";
                camera.BusyStatus(start_address, ref result);
                string str = camera.ParseCameraBusy(result);
                if (str == "00")
                {
                    return true;  // 相机空闲
                }
                else
                {
                    return false; //相机忙
                }

            }
            return false;
        }

    }
}
